<template>
  <div class="form-div">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="form.deptName"></el-input>
      </el-form-item>
      <el-form-item label="上级部门">
        <el-select v-model="selectedDepartment" placeholder="请选择上级部门" clearable>
          <el-option v-for="item in departmentList" :key="item.id" :label="item.deptName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门级别" prop="level">
        <el-input v-model="form.level" type="number"></el-input>
      </el-form-item>
      <el-form-item label="负责人" prop="deptHead">
        <el-input v-model="form.deptHead"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactNumber">
        <el-input v-model="form.contactNumber"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save(formRef)">提交</el-button>
        <el-button @click="$emit('close')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {editDepartmentApi, getDepartmentListApi} from "@/assets/api/system/department";
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";

const props = defineProps({
  form: {
    deptName: String,
    pid: Number,
    pDeptName: String,
    level: Number,
    deptHead: String,
    contactNumber: String,
    remark: String
  }
})

const emit = defineEmits(['close', 'save'])

// 获取所有部门列表
const departmentList = ref([])
const selectedDepartment = ref(props.form.pid);
const getDepartmentList = () => {
  getDepartmentListApi().then(res => {
    departmentList.value = res.data.data;
  })
}

// 表单验证
const formRef = ref();
const rules = ref({
  deptName: [
    {required: true, message: '请输入部门名称', trigger: 'blur'}
  ],
  level: [
    {required: true, message: '请输入部门级别', trigger: 'blur'}
  ],
  deptHead: [
    {required: true, message: '请输入负责人', trigger: 'blur'}
  ],
  contactNumber: [
    {required: true, message: '请输入联系电话', trigger: 'blur'}]
})


// 保存
const save = async (formEl) => {
  props.form.pid = selectedDepartment.value;
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      editDepartmentApi(props.form).then(res => {
        if (res.data.code === 200) {
          ElMessage.info("保存成功")
          emit('save', true);
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    }
  })
}

onMounted(() => {
  getDepartmentList();
})
</script>

<style scoped>

</style>